package com.qboot.common.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qboot.common.consts.MsgConst;
import com.qboot.common.entity.Result;
import com.qboot.common.utils.SpringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制层 基类
 *
 * @author Tellsea
 * @date 2022/11/25
 */
public class BaseController {

    public static final String PAGE_NUM = "pageNum";

    public static final String PAGE_SIZE = "pageSize";

    public static final int PAGE_NUM_DEFAULT = 1;

    public static final int PAGE_SIZE_DEFAULT = 100000;

    public static Page getPage() {
        int pageNum = PAGE_NUM_DEFAULT;
        int pagSize = PAGE_SIZE_DEFAULT;
        HttpServletRequest request = SpringUtils.getRequest();
        if (StrUtil.isNotEmpty(request.getParameter(PAGE_NUM)) && Integer.valueOf(request.getParameter(PAGE_NUM)) > 0) {
            pageNum = Integer.parseInt(request.getParameter(PAGE_NUM));
        }
        if (StrUtil.isNotEmpty(request.getParameter(PAGE_SIZE)) && Integer.valueOf(request.getParameter(PAGE_SIZE)) > 0) {
            pagSize = Integer.parseInt(request.getParameter(PAGE_SIZE));
        }
        return new Page(pageNum, pagSize);
    }

    public static Page getAllPage() {
        return new Page(PAGE_NUM_DEFAULT, PAGE_SIZE_DEFAULT);
    }

    public static <T> Result queryResult(T data) {
        return Result.ok(MsgConst.QUERY_SUCCESS, data);
    }

    public static Result saveResult(boolean flag) {
        return flag ? Result.ok(MsgConst.SAVE_SUCCESS) : Result.fail(MsgConst.SAVE_ERROR);
    }

    public static Result updateResult(boolean flag) {
        return flag ? Result.ok(MsgConst.UPDATE_SUCCESS) : Result.fail(MsgConst.UPDATE_ERROR);
    }

    public static Result removeResult(boolean flag) {
        return flag ? Result.ok(MsgConst.REMOVE_SUCCESS) : Result.fail(MsgConst.REMOVE_ERROR);
    }
}
